<?php 

namespace app\nideshop\controller;

use think\Db;
use app\nideshop\validate\GoodsValidate;
use app\nideshop\service\Token;

class Goods extends Base
{	
	/**
	 * 接收请求参数
	 * @var [type]
	 */
	protected $datas;

	/**
	 * 对应数据表
	 * @var string
	 */
	protected $table = 'goods';

	/**
	 * 统计商品总数
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-21T23:58:36+0800
	 * @return   [type]                   [description]
	 */
	public function countAction()
	{
		$goodsCount = Db::name($this->table)->where(['is_delete' => 0, 'is_on_sale' => 1])->count('id');
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'goodsCount' => $goodsCount
			]
		]);
	}

	/**
	 * 商品列表
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-20T23:28:24+0800
	 * @return   [type]                   [description]
	 */
	public function listAction()
	{
		$this->datas = $this->params;
		$validate = new GoodsValidate();
		if (!$validate->scene('list')->check($this->datas)) {
			return json(['errno' => 1, 'errmsg' => $validate->getError(), 'data' => []]);
		}
		$categoryId = $this->datas['categoryId'];
		$page = $this->datas['page'];
		$size = $this->datas['size'];
		$brandId = isset($this->datas['brandId']) ? $this->datas['brandId'] : '';
		$keyword = isset($this->datas['keyword']) ? $this->datas['keyword'] : '';
		$isNew = isset($this->datas['isNew']) ? $this->datas['isNew'] : '';
		$isHot = isset($this->datas['isHot']) ? $this->datas['isHot'] : '';
		$sort = isset($this->datas['sort']) ? $this->datas['sort'] : '';
		$order = isset($this->datas['order']) ? $this->datas['order'] : '';
		$whereMap = [];
		//这里有个bug，传0有问题
		if (!empty($isNew)){
			$whereMap[] = ['is_new', '=', $isNew];
		}
		if (!empty($isHot)) {
			$whereMap[] = ['is_hot', '=', $isHot];
		}
		if (!empty($keyword)) {
			$whereMap[] = ['name', 'like', '%' . $keyword . '%'];
			//添加历史搜索
		}
		if (!empty($brandId)) {
			$whereMap['brand_id'] = $brandId;
		}
		if ($sort === 'price') {
			$orderMap['retail_price'] = $order;
		} else {
			$orderMap['id'] = 'desc';
		}
		$filterCategory = [
	        [
	        	'id' => 0,
		        'name' => '全部',
		        'checked' => false
	    	]
	    ];
		$categoryIds = Db::name($this->table)->where($whereMap)->column('category_id');
		if (!empty($categoryIds)) {
			//查找二级分类的parent_id
			$parentIds = Db::name('category')->whereIn('id', $categoryIds)->column('parent_id');
			//一级分类
			$parentCategory = Db::name('category')->order('sort_order', 'ASC')->whereIn('id', $parentIds)->select();
			if (!empty($parentCategory)) {
				foreach ($parentCategory as $key => $val) {
					$filterCategory[$key+1]['id'] = $val['id'];
					$filterCategory[$key+1]['name'] = $val['name'];
					$filterCategory[$key+1]['checked'] = false;
				}
			}
		}
		foreach ($filterCategory as $key => $val) {
			if ($categoryId === 0) {
				$filterCategory[0]['checked'] = true;
			}
			if ($val['id'] == $categoryId) {
				$filterCategory[$key]['checked'] = true;
			}
		}
		if (!empty($categoryId) && $categoryId > 0) {
			$categoryIdArr = Db::name('category')->where('parent_id', $categoryId)->column('id');
			array_push($categoryIdArr, $categoryId);
			$whereMap[] = ['category_id', 'in', $categoryIdArr];
		}
		$goodsObj = Db::name($this->table)
			->where($whereMap)
			->field('id,name,list_pic_url,retail_price')
			->order($orderMap)
			->paginate($size, false, ['page' => $page]);
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'count' => $goodsObj->total(),
				'totalPages' => $goodsObj->lastPage(),
				'pageSize' => (int)$size,
				'currentPage' => (int)$page,
				'data' => $goodsObj->items(),
				'filterCategory' => $filterCategory,
				'goodsList' => $goodsObj->items()
			]
		]);
	}

	/**
	 * 商品详情
	 * @Author   Yichen
	 * @DateTime 2020-05-22T22:05:52+0800
	 * @return   [type]                   [description]
	 */
	public function detailAction()
	{
		$this->datas = $this->params;
		$validate = new GoodsValidate();
		if (!$validate->scene('detail')->check($this->datas)) {
			return json(['errno' => 1, 'errmsg' => $validate->getError(), 'data' => []]);
		}
		$goodsId = $this->datas['id'];
		$userId = 0;
		if (!empty($_SERVER['HTTP_X_NIDESHOP_TOKEN'])) {
			$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
		}
		$info = Db::name($this->table)->where('id', $goodsId)->find();
		$gallery = Db::name('goods_gallery')->where('goods_id', $goodsId)->limit(4)->select();
		$attribute = Db::name('goods_attribute')->alias('ga')
			->join('attribute a', 'ga.attribute_id=a.id', 'LEFT')
			->where('ga.goods_id', $goodsId)
			->order('ga.id', 'ASC')
			->field('ga.value,a.name')
			->select();
		$issue = Db::name('goods_issue')->field('id,goods_id,question,answer')->select();
		$brand = Db::name('brand')->where('id', $info['brand_id'])->find();
		$commentCount = Db::name('comment')->where(['value_id' => $goodsId, 'type_id' => 0])->count();
		$hotComment = Db::name('comment')->where(['value_id' => $goodsId, 'type_id' => 0])->find();
		$commentInfo = [];
		if (!empty($hotComment)) {
			$commentUser = Db::name('user')->where('id', $hotComment['user_id'])->field('nickname,username,avatar')->find();
			$commentInfo['content'] = base64_decode($hotComment['content']);
			$commentInfo['add_time'] = $hotComment['add_time'];
			$commentInfo['nickname'] = $commentUser['nickname'];
			$commentInfo['avatar'] = $commentUser['avatar'];
			$commentInfo['pic_list'] = Db::name('comment_picture')
				->where('comment_id', $hotComment['id'])
				->field('id,comment_id,pic_url,sort_order')
				->select();
		}
		// 当前用户是否收藏
      	$isUserHasCollect = 0;
      	// 记录用户的足迹 TODO
      	if ($userId > 0) {
      		Db::name('footprint')->insert([
		        'goods_id' => $goodsId,
		        'user_id' => $userId,
		        'add_time' => time()
		    ]);
      	}
      	$specificationRes = Db::name('goods_specification')->alias('gs')
      		->join('specification s', 's.id=gs.specification_id', 'LEFT')
      		->where('gs.goods_id', $goodsId)
      		->field('gs.*,s.name')
      		->select();
      	$specificationList = [];
      	$list = [];
      	//按照规格分组
      	foreach ($specificationRes as $key => $val) {
      		$list[$val['specification_id']][] = $val;
      	}	
      	$list = array_merge($list);
      	foreach ($list as $key => $val) {
      		$specificationList[$key]['specification_id'] = $val[0]['specification_id'];
      		$specificationList[$key]['name'] = $val[0]['name'];
      		$specificationList[$key]['valueList'] = $val;
      	}
      	$productList = Db::name('product')->where('goods_id', $goodsId)->select();
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'info' => $info,
				'gallery' => $gallery,
				'attribute' => $attribute,
				'userHasCollect' => $isUserHasCollect,
				'issue' => $issue,
				'comment' => $commentInfo,
				'brand' => $brand,
				'specificationList' => $specificationList,
				'productList' => $productList
			]
		]);
	}

	/**
	 * 商品详情页的大家都在看的商品
	 * @Author   Yichen
	 * @DateTime 2020-05-23T11:20:54+0800
	 * @return   [type]                   [description]
	 */
	public function relatedAction()
	{
		$this->datas = $this->params;
		$validate = new GoodsValidate();
		if (!$validate->scene('detail')->check($this->datas)) {
			return json(['errno' => 1, 'errmsg' => $validate->getError(), 'data' => []]);
		}
		$goodsId = $this->datas['id'];
		$relatedGoodsIds = Db::name('related_goods')->where('goods_id', $goodsId)->value('related_goods_id');
		if (!empty($relatedGoodsIds)) {
			$relatedGoods = Db::name($this->table)
				->whereIn('id', $relatedGoodsIds)
				->field('id,name,list_pic_url,retail_price')
				->select();
		} else {
			$goodsCategory = Db::name($this->table)->where('id', $goodsId)->find();
			$relatedGoods = Db::name($this->table)
				->where('category_id', $goodsCategory['category_id'])
				->field('id,name,list_pic_url,retail_price')
				->limit(8)
				->select();
		}
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'goodsList' => $relatedGoods
			]
		]);
	}
}